var express = require('express');
var router = express.Router();
var checkLogin =require('../middleware/checkLogin');
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var mock=require('../models/mock');
module.exports = router;

//发表
router.get('/',checkLogin, function (req, res) {
  res.render('post',{title:'发表',user:req.session.user,success:req.flash('success').toString(),error:req.flash('error').toString()});
});

router.post('/',checkLogin, function (req, res) {
  var post,user;
  if(!req.body.title.trim().length || !req.body.content.trim().length){
    req.flash('error','博客填写错误');
    return res.redirect('/post');
  }
  //console.log('new Post->req.session.user._id:',req.session.user._id,typeof req.session.user._id);

  user=req.session.user;
  //console.log('new Post->content:',req.body);
  //console.log('new Post->user._id:',user._id,typeof user._id);
  post=new Post({
    title:req.body.title,
    tags:req.body.tag,
    desc:req.body.desc,
    content:req.body.content,
    user:{
      _id:user._id,
      name:user.name,
      email:user.email,
      face:user.face
    },
    date:new Date()
  });
  //console.log('new Post->newPost:',post);

  post.save(function (err) {
    if(err){
      req.flash('error','发表失败');
      return res.redirect('/post');
    }
    req.flash('success','发表成功');
    //console.log('/post > post:',post);
    res.redirect('back');
  });
});